<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-card class="search-card">
      <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
        <el-form-item label="订单号" prop="orderNumber">
          <el-input
            v-model="queryParams.orderNumber"
            placeholder="请输入订单号"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="订单状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="订单状态" clearable style="width: 200px">
            <el-option label="待付款" value="PENDING_PAYMENT" />
            <el-option label="待发货" value="PENDING_SHIPMENT" />
            <el-option label="已发货" value="SHIPPED" />
            <el-option label="已完成" value="COMPLETED" />
            <el-option label="已取消" value="CANCELLED" />
          </el-select>
        </el-form-item>
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="queryParams.username"
            placeholder="请输入用户名"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作工具栏 -->
    <el-card class="toolbar-card">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
          >修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
          >删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
          >导出</el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 订单表格 -->
    <el-card>
      <el-table
        v-loading="loading"
        :data="orderList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="订单号" align="center" prop="orderNumber" width="180" />
        <el-table-column label="用户信息" align="center" width="150">
          <template #default="scope">
            <div>
              <div>{{ scope.row.username }}</div>
              <div class="text-muted">{{ scope.row.userPhone }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="商品信息" align="center" min-width="200">
          <template #default="scope">
            <div class="product-info">
              <div v-for="item in scope.row.items.slice(0, 2)" :key="item.id" class="product-item">
                <el-image
                  :src="item.product.image || '/default-product.jpg'"
                  fit="cover"
                  class="product-image"
                />
                <div class="product-details">
                  <div class="product-name">{{ item.product.name }}</div>
                  <div class="product-spec">{{ item.quantity }}件 × ¥{{ item.price }}</div>
                </div>
              </div>
              <div v-if="scope.row.items.length > 2" class="more-products">
                +{{ scope.row.items.length - 2 }}件商品
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="订单金额" align="center" width="120">
          <template #default="scope">
            <div class="amount-info">
              <div class="total-amount">¥{{ scope.row.totalAmount }}</div>
              <div class="product-amount text-muted">商品: ¥{{ scope.row.productAmount }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="订单状态" align="center" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="支付方式" align="center" prop="paymentMethod" width="100" />
        <el-table-column label="创建时间" align="center" prop="createTime" width="180">
          <template #default="scope">
            <span>{{ formatDateTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button
              type="primary"
              icon="View"
              @click="handleView(scope.row)"
              link
            >查看</el-button>
            <el-button
              v-if="scope.row.status === 'PENDING_SHIPMENT'"
              type="success"
              icon="Truck"
              @click="handleShip(scope.row)"
              link
            >发货</el-button>
            <el-button
              type="danger"
              icon="Delete"
              @click="handleDelete(scope.row)"
              link
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <Pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 发货对话框 -->
    <el-dialog
      v-model="shipDialog.visible"
      title="订单发货"
      width="500px"
    >
      <el-form :model="shipDialog.form" label-width="100px">
        <el-form-item label="物流公司">
          <el-select v-model="shipDialog.form.logisticsCompany" placeholder="请选择物流公司">
            <el-option label="顺丰速运" value="SF" />
            <el-option label="圆通速递" value="YTO" />
            <el-option label="中通快递" value="ZTO" />
            <el-option label="申通快递" value="STO" />
            <el-option label="韵达速递" value="YD" />
          </el-select>
        </el-form-item>
        <el-form-item label="快递单号">
          <el-input v-model="shipDialog.form.trackingNumber" placeholder="请输入快递单号" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="shipDialog.form.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="shipDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="confirmShip" :loading="shipDialog.loading">确定发货</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getOrderPage, deleteOrder, shipOrder, exportOrders } from '@/api/mall'
import { useRouter } from 'vue-router'
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination/index.vue'

const router = useRouter()

// 响应式数据
const loading = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const orderList = ref([])
const queryFormRef = ref()
const dateRange = ref([])

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  orderNumber: undefined,
  status: undefined,
  username: undefined,
  startTime: undefined,
  endTime: undefined
})

// 发货对话框
const shipDialog = reactive({
  visible: false,
  loading: false,
  orderId: null,
  form: {
    logisticsCompany: '',
    trackingNumber: '',
    remark: ''
  }
})

// 获取订单列表
const getList = async () => {
  loading.value = true
  try {
    if (dateRange.value && dateRange.value.length === 2) {
      queryParams.startTime = dateRange.value[0]
      queryParams.endTime = dateRange.value[1]
    } else {
      queryParams.startTime = undefined
      queryParams.endTime = undefined
    }
    
    const response = await getOrderPage(queryParams)
    if (response.code === 200) {
      orderList.value = response.data.records || []
      total.value = response.data.total || 0
    } else {
      ElMessage.error(response.message || '获取订单列表失败')
    }
  } catch (error) {
    console.error('获取订单列表失败:', error)
    ElMessage.error('获取订单列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索按钮操作
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 重置按钮操作
const resetQuery = () => {
  dateRange.value = []
  queryFormRef.value?.resetFields()
  handleQuery()
}

// 多选框选中数据
const handleSelectionChange = (selection) => {
  ids.value = selection.map(item => item.id)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

// 查看按钮操作
const handleView = (row) => {
  router.push(`/mall/order/detail/${row.id}`)
}

// 修改按钮操作
const handleUpdate = (row) => {
  const orderId = row.id || ids.value[0]
  router.push(`/mall/order/edit/${orderId}`)
}

// 发货按钮操作
const handleShip = (row) => {
  shipDialog.orderId = row.id
  shipDialog.form = {
    logisticsCompany: '',
    trackingNumber: '',
    remark: ''
  }
  shipDialog.visible = true
}

// 确认发货
const confirmShip = async () => {
  if (!shipDialog.form.logisticsCompany || !shipDialog.form.trackingNumber) {
    ElMessage.warning('请填写物流公司和快递单号')
    return
  }
  
  try {
    shipDialog.loading = true
    await shipOrder(shipDialog.orderId, shipDialog.form)
    ElMessage.success('发货成功')
    shipDialog.visible = false
    getList()
  } catch (error) {
    console.error('发货失败:', error)
    ElMessage.error('发货失败')
  } finally {
    shipDialog.loading = false
  }
}

// 删除按钮操作
const handleDelete = (row) => {
  const orderIds = row.id ? [row.id] : ids.value
  ElMessageBox.confirm('是否确认删除订单编号为"' + orderIds + '"的数据项？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteOrder(orderIds[0])
      getList()
      ElMessage.success('删除成功')
    } catch (error) {
      console.error('删除订单失败:', error)
      ElMessage.error('删除订单失败')
    }
  }).catch(() => {})
}

// 导出按钮操作
const handleExport = async () => {
  try {
    await exportOrders(queryParams)
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  }
}

// 工具函数
const formatDateTime = (time) => {
  if (!time) return ''
  const date = new Date(time)
  return date.toLocaleString()
}

const getStatusType = (status) => {
  const typeMap = {
    'PENDING_PAYMENT': 'warning',
    'PENDING_SHIPMENT': 'info',
    'SHIPPED': 'primary',
    'COMPLETED': 'success',
    'CANCELLED': 'danger'
  }
  return typeMap[status] || 'info'
}

const getStatusText = (status) => {
  const textMap = {
    'PENDING_PAYMENT': '待付款',
    'PENDING_SHIPMENT': '待发货',
    'SHIPPED': '已发货',
    'COMPLETED': '已完成',
    'CANCELLED': '已取消'
  }
  return textMap[status] || status
}

// 页面加载时获取数据
onMounted(() => {
  getList()
})
</script>

<style lang="scss" scoped>
.search-card {
  margin-bottom: 16px;
}

.toolbar-card {
  margin-bottom: 16px;
}

.mb8 {
  margin-bottom: 8px;
}

.product-info {
  .product-item {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 8px;
    
    .product-image {
      width: 40px;
      height: 40px;
      border-radius: 4px;
    }
    
    .product-details {
      flex: 1;
      text-align: left;
      
      .product-name {
        font-size: 12px;
        color: #303133;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      
      .product-spec {
        font-size: 11px;
        color: #909399;
      }
    }
  }
  
  .more-products {
    font-size: 12px;
    color: #909399;
    text-align: center;
  }
}

.amount-info {
  .total-amount {
    font-weight: bold;
    color: #e6a23c;
  }
  
  .product-amount {
    font-size: 12px;
  }
}

.text-muted {
  color: #909399;
  font-size: 12px;
}
</style>
